package _04file
/*
文件操作
 */

def file = new File("d://a.txt")
//逐行读取
file.eachLine { line ->
    //println line
}
//一次性读取
//println file.getText()

//返回每一行的list
def lines = file.readLines()
//println lines

//读取部分字符
def reader1 = file.withReader { reader ->
    char[] buf = new char[2]
    reader.read(buf)//读到buf中
    return buf
}

//闭包方式创建无需关闭，newReader类似java，new一个对象，所以需要关闭
file.newReader()

println reader1

copy("d://a.txt", "d://a_copy.txt")
//文件拷贝
def copy(String src, String desc) {
    def descFile = new File(desc)
    if (!descFile.exists()) {
        descFile.createNewFile()
    }

    //文件读写无需关闭流，Groovy在底层帮助我们处理
    def srcFile = new File(src)
    srcFile.withReader { reader ->
        def lines = reader.readLines()//读出一行写入到descfile中
        descFile.withWriter { writer ->
            lines.each { line ->
                writer.append(line)
            }
        }
    }
}